from bottle import route, run, template, static_file
from threading import Thread
import time
from thermostat import Thermostat
from userSettings import UserSettings
import os.path
import pickle

settings = UserSettings()
if(os.path.exists(settings.settingsFileName)):
        settings = pickle.load(open(settings.settingsFileName,"rb"))

therm = Thermostat(0.5,settings)

@route('/')
def index():
        return static_file("index.html", root=settings.basePath)

@route('/getCurrentTemp')
def getCurrentTemp():
        return str(therm.getCurrentTemp())

@route('/getCurrentHumidity')
def getCurrentHumidity():
        return str(therm.getCurrentHumidity())

@route('/isHeatingManually')        
def isHeatingManually():
        return str(therm.isHeatingManually())

@route('/toggleHeat')
def toggleHeat():
        therm.toggleHeat()
        return isHeatingManually()

@route('/isHeating')
def isHeating():
        return str(therm.isHeating())
        

@route('/setDesiredTemp/:desiredTemp')
def setDesiredTemp(desiredTemp):
        therm.setDesiredTemp(float(desiredTemp))

@route('/getDesiredTemp')
def getDesiredTemp():
        return str(therm.getDesiredTemp())

def runServer():
        run(host='0.0.0.0')

#start the web server
server = Thread(target = runServer)
server.setDaemon(True)
server.start()

#main thermostat loop
while(True):
        time.sleep(2)
        therm.update()
        
